/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wx.handler;

import cn.ac.iie.di.wx.httpservice.HttpSender;
import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import cn.ac.iie.di.commons.httpserver.framework.util.ParseRequestStream;
import cn.ac.iie.di.wx.common.RuntimeEnv;
import cn.ac.iie.di.wx.utils.IDSHAGeneratorImpl;
import cn.ac.iie.di.wx.vo.RealIDQueryVo;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;

/**
 *
 * @author Administrator
 */
public class WxRealIdQuery implements HandlerI {

    static Logger logger = Logger.getLogger(WxRealIdQuery.class.getName());

    @Override
    public void execute(Request pRequest, HttpServletRequest request, HttpServletResponse response) throws Exception {
//        MongoHelper mongoHelper = null;
        try {

            byte[] bytesContent = new byte[1024 * 2];
            int bytesReadIn = 0;
            ServletOutputStream out = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(out);
            //获取id字段，进行拼接后发送response,http连接资源释放问题需要注意
            String idJson = ParseRequestStream.parseRequestStreamAsString(pRequest.getInputStream());
            idJson=java.net.URLDecoder.decode(idJson, "utf-8");
            logger.info(idJson);
            HttpSender hs = new HttpSender();
            String result = "";
            if (RuntimeEnv.wxRealIdQueryLimit.incrementAndGet() <= Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.WXREALIDQLIMIT))) {
                RuntimeEnv.wxRealIdQueryCount.incrementAndGet();
                try {
                    //拼接命令
                    String realidresult = hs.sendStringByUrl(idJson, (String) RuntimeEnv.getParam(RuntimeEnv.wxRealIdQueryUrl));//json的字符串
                    if (!realidresult.isEmpty()) {
                        logger.info(realidresult);
                        JSONObject jSONObject = JSONObject.parseObject(realidresult);
                        String data = jSONObject.getString("data");
                        if (!data.isEmpty()) {
                            JSONObject read_idObject = JSONObject.parseObject(data);//获取的阅读数
                            String realId = read_idObject.getString("wxid");
                            if (!realId.isEmpty()) {
                                result = realidresult;
                                JSONObject requestObject = JSONObject.parseObject(idJson);
                                String wxid = requestObject.getString("wxid");
                                logger.info(wxid);
                                RuntimeEnv.realIdWxUserOldBlockingQueue.add(new RealIDQueryVo(IDSHAGeneratorImpl.getId("40", "U-WX03-A", "WeChat", "WeChat", wxid), realId));
                                RuntimeEnv.realIdWxUserNewBlockingQueue.add(new RealIDQueryVo(IDSHAGeneratorImpl.getId("40", "U-WX03-A", "WeChat", "WeChat", wxid), realId));

                            } else {
                                result = realidresult;
                                logger.info("realId is empty");
                            }
                        } else {
                            result = realidresult;
                            String errorinfo = jSONObject.getString("errorinfo");
                            logger.info("WxRealIdQuery get error mesasge" + errorinfo);
                        }
                    } else {
                        result = "{\"code\":-3,\"errorinfo\":\"请求超时\",\"data\":\"\"}";
                        logger.info("WxRealIdQuery httpClient connect out of time");
                    }

                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }

            } else {
                result = "{\"code\":-4,\"errorinfo\":\"查询访问量超限\",\"data\":\"\"}";
                logger.info("WxRealIdQuery httpClient connection size is limited ");
            }
            //释放连接
//            Thread.sleep(1000);
            InputStream inputStream = new ByteArrayInputStream(result.getBytes("UTF-8"));

            while ((bytesReadIn = inputStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                bos.write(bytesContent, 0, bytesReadIn);
            }
            bos.flush();
            bos.close();
            RuntimeEnv.wxRealIdQueryLimit.decrementAndGet();
        } catch (Exception e) {
            logger.error("Filedownload send out error\n" + e.getMessage(), e);
        }
    }

    @Override
    public void init() throws Exception {

    }
}
